package com.zk.babala.util;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.core.content.FileProvider;

import com.zk.babala.R;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @Author: zhangke
 * @Date: 2023/5/18 15:49
 */
public class UpdateApp {

    // 下载线程
    private Thread downLoadThread;
    private int progress;// 当前进度
    // 应用程序Context
    private Context mContext;
    private ProgressBar mProgress;
    private TextView txtStatus;
    private boolean intercept = false;
    private File apkFile;
    private static final int DOWN_UPDATE = 1;
    private static final int DOWN_OVER = 2;
    private static final int SHOWDOWN = 3;
    private AlertDialog updateDialog;
    // 保存APK的文件夹
    private static String savePath;
    //apk文件的绝对路径
    private static String saveFileName;

    public UpdateApp(Context context) {
        mContext = context;
    }

    public void ShowDownloadDialog() {
        AlertDialog.Builder dialog = new AlertDialog.Builder(mContext);
        dialog.setTitle("软件版本更新");
        LayoutInflater inflater = LayoutInflater.from(mContext);
        View v = inflater.inflate(R.layout.progress, null);
        mProgress = (ProgressBar) v.findViewById(R.id.progress);
        txtStatus = v.findViewById(R.id.txtStatus);
        dialog.setView(v);
        dialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                intercept = true;
                dialog.dismiss();
            }
        });
        updateDialog = dialog.create();
        updateDialog.show();
        downloadApk();
    }

    /**
     * 从服务器下载APK安装包
     */
    private void downloadApk() {
        savePath = mContext.getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS) + "/";
        downLoadThread = new Thread(downApkRunnable);
        downLoadThread.start();
    }

    //下载安装包的进程，同步更新安装包的下载进度，以及下载完成后的通知安装
    private Runnable downApkRunnable = new Runnable() {
        @Override
        public void run() {
            URL url;

            try {
                //对sd卡进行状态的判断，如果相等的话表示当前的sdcard挂载在手机上并且是可用的
                if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {

                    url = new URL(GiteeUtil.APP_FILE_URL);
                    HttpURLConnection conn = (HttpURLConnection) url
                            .openConnection();
                    conn.connect();
                    int length = conn.getContentLength();
                    InputStream ins = conn.getInputStream();
                    //创建安装包所在的前置文件夹
                    File file = new File(savePath);
                    if (!file.exists()) {
                        file.mkdir();
                    }
                    //创建安装包的文件，安装包将下载入这个文件夹中
                    saveFileName = savePath + "babala.apk";
                    File apkFile = new File(saveFileName);
                    file.deleteOnExit();
                    //创建该文件夹的输入流
                    FileOutputStream fos = new FileOutputStream(apkFile);
                    int count = 0;
                    byte[] buf = new byte[1024];
                    while (!intercept) {//对取消下载的标志位进行判断，如果一直没有被打断即没有点击取消下载按钮则继续下载
                        int numread = ins.read(buf);//返回读入的字节个数并将读到的字节内容放入buf中
                        count += numread;
                        progress = (int) (((float) count / length) * 100);//当前进度，用来更新progressBar的进度

                        // 通知主线程更新下载进度
                        mHandler.sendEmptyMessage(DOWN_UPDATE);
                        if (numread <= 0) {
                            // 下载完成通知安装
                            mHandler.sendEmptyMessage(DOWN_OVER);
                            break;
                        }
                        //已经全部读入，不需要再读入字节为-1的内容
                        fos.write(buf, 0, numread);//从fos中写入读出的字节个数到buf中
                    }

                    fos.close();
                    ins.close();
                } else
                    return;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

    /**
     * 安装APK内容
     */
    private void installAPK() {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);//设置启动模式，四种之一
        File apkFile = new File(saveFileName);

        Uri uri;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {// 前面代表的是当前操作系统的版本号，后面是给定的版本号，Ctrl鼠标放置显示版本号
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            //记得修改com.xxx.fileprovider与androidmanifest相同
            // 获取的是应用唯一区分的id即applicationId
            uri = FileProvider.getUriForFile(mContext, "com.zk.babala.fileprovider", apkFile);
            intent.setDataAndType(uri, "application/vnd.android.package-archive");// 打开apk文件
        } else {
            uri = Uri.parse("file://" + apkFile.toString());
        }
        intent.setDataAndType(uri, "application/vnd.android.package-archive");
        mContext.startActivity(intent);
    }

    private Handler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case DOWN_UPDATE:
                    txtStatus.setText(progress + "%");
                    mProgress.setProgress(progress);
                    break;
                case DOWN_OVER:
                    Toast.makeText(mContext, "下载完毕", Toast.LENGTH_SHORT).show();
                    installAPK();
                    break;
                default:
                    break;
            }
        }

    };
}
